package com.jgsu.farm.controller;

import com.jgsu.farm.entity.User;
import com.jgsu.farm.service.AdminService;
import com.jgsu.farm.utils.CommonResult;
import com.jgsu.farm.utils.ResultCode;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * @program: farm-10-14-2019
 * @description: 管理员接口
 * @author: Mr.zuo
 * @create: 2019-12-05 16:17
 **/
@RestController
@Slf4j
@RequestMapping("farm/sysuser")
public class AdminController {

    @Autowired
    AdminService adminService;

      @ApiOperation(value = "管理员登录后台功能")
      @PostMapping(value = "/login", produces = "application/json")
      public CommonResult loginSysUser(String phone,String password, HttpSession session) {
          User sysUser = adminService.loginSysUser(phone, password, 1);
          if (phone.equals(sysUser.getPhone())&&password.equals(sysUser.getPassword())) {
              // 获取session，供拦截器拿到而判断用户是否登录
              session.setAttribute("phone",phone);
              ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
              //将登陆用户信息存入到session域对象中
              attributes.getRequest().getSession().setAttribute("phone", phone);
              log.info("管理员登录，phone为{},password为{}",phone,password);
              return CommonResult.success(ResultCode.SUCCESS);
          }else {
              return CommonResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
          }
      }
      /**
       * 管理员注销
       *
       * @return
       */
      @PostMapping(value = "/logout",produces = "application/json")
      public CommonResult logout(HttpSession session) {
          ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
           if (session.getAttribute("phone") !=  null){
               attributes.getRequest().getSession().removeAttribute("phone");
               log.info("注销成功。。。");
               return CommonResult.success(ResultCode.SUCCESS);
           }else {
               log.error("未登录，注销失败");
               return CommonResult.failed(ResultCode.UNAUTHORIZED);
           }
      }
}
